package com.jdwx.opengl.face.utils;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.os.Build;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * ****************************
 * Project：
 *
 * @AUTHER： YBB
 * CreateTime：2020/6/15 19:54
 * Describe：
 * ****************************
 */
public class DFacePermission {

    private static final int PERMISSIONS_REQUEST = 1;
    private final String PERMISSION_CAMERA = Manifest.permission.CAMERA;
    private final String PERMISSION_STORAGE = Manifest.permission.WRITE_EXTERNAL_STORAGE;
    private final String PERMISSION_READ_STORAGE = Manifest.permission.READ_EXTERNAL_STORAGE;
    private final String TAG = "DFacePermission";

    private Activity activity;

    public DFacePermission(Activity activity){
        this.activity  = activity;
    }

    public void Permission(){
        if (hasPermission()) {
            mkdirs();
            //拷贝assert的normal_binary文件夹到sd卡的dface目录
            copyAssertToSdCard("normal_binary");
        } else {
            requestPermission();
        }
    }

    /**
     * @return 判断是否授权
     */
    private boolean hasPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return activity.checkSelfPermission(PERMISSION_CAMERA) == PackageManager.PERMISSION_GRANTED &&
                    activity.checkSelfPermission(PERMISSION_STORAGE) == PackageManager.PERMISSION_GRANTED;
        } else {
            return true;
        }
    }

    /**
     * 请求授权
     */
    private void requestPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (activity.shouldShowRequestPermissionRationale(PERMISSION_CAMERA) || activity.shouldShowRequestPermissionRationale(PERMISSION_READ_STORAGE) ||
                    activity.shouldShowRequestPermissionRationale(PERMISSION_STORAGE)) {
                Toast.makeText(activity,
                        "Camera AND storage permission are required for this demo", Toast.LENGTH_LONG).show();
            }
            activity.requestPermissions(new String[] {PERMISSION_CAMERA, PERMISSION_STORAGE,PERMISSION_READ_STORAGE}, PERMISSIONS_REQUEST);
        }
    }

    /**
     * 创建目录
     */
    private void mkdirs(){
        File sdDir = Environment.getExternalStorageDirectory();//获取跟目录
        File file = new File(sdDir.toString()+"/dface/");
        if (!file.exists()) {
            file.mkdir();
        }

        //创建faceimg目录
        File fileImg = new File(sdDir.toString()+"/dface/faceimg");
        if (!fileImg.exists()) {
            fileImg.mkdir();
        }

        //创建日志目录
        File fileLog = new File(sdDir.toString()+"/dface/logs");
        if (!fileLog.exists()) {
            fileLog.mkdir();
        }

        //创建数据库db目录
        File fileDB = new File(sdDir.toString()+"/dface/db");
        if (!fileDB.exists()) {
            fileDB.mkdir();
        }
    }

    /**
     * 拷贝assert目录到SD卡
     */
    private void copyAssertToSdCard(String path) {
        File sdDir = Environment.getExternalStorageDirectory();//获取跟目录
        File file = new File(sdDir.toString()+"/dface/");
        if (!file.exists()) {
            file.mkdir();
        }

        //拷贝assert/normal_binary目录下的模型文件到sd卡的dface/normal_binary
        AssetManager assetManager = activity.getAssets();
        String assets[] = null;
        try {
            assets = assetManager.list(path);
            if (assets.length == 0) {
                copyFile(path);
            } else {
                String fullPath =  file.toString() + "/" + path;
                File dir = new File(fullPath);
                if (!dir.exists())
                    dir.mkdir();
                for (int i = 0; i < assets.length; ++i) {
                    copyAssertToSdCard(path + "/" + assets[i]);
                }
            }
        } catch (IOException ex) {
            Log.e(TAG, "I/O Exception");
        }
    }

    /**
     * 拷贝模型到SD卡的dface目录(只拷贝原先不存在的文件)
     */
    private void copyFile(String filename) {
        File sdDir = Environment.getExternalStorageDirectory();//获取跟目录
        File file = new File(sdDir.toString()+"/dface/");
        if (!file.exists()) {
            file.mkdir();
        }

        AssetManager assetManager = activity.getAssets();
        InputStream in = null;
        OutputStream out = null;
        try {
            in = assetManager.open(filename);
            String newFileName = file.toString() + "/" + filename;

            out = new FileOutputStream(newFileName);

            byte[] buffer = new byte[1024];
            int read;
            while ((read = in.read(buffer)) != -1) {
                out.write(buffer, 0, read);
            }
            in.close();
            in = null;
            out.flush();
            out.close();
            out = null;
        } catch (Exception e) {
            Log.e("tag", e.getMessage());
        }
    }
}